#include "utilities.h"

void init_utilities(){
	DDRB |= (1 << DDB0);
}

void print_text(char* text){
	// Count the amount of characters
	uint8_t chars = 0;
	while(text[chars]!='\0'){
		chars++;
	}
	// Send cmd with params (length of the text and the text itself)
	uint8_t length = chars + 1;
	uint8_t* params = malloc(length);
	params[0] = chars;
	memcpy(params+1,text,chars);
	send_cmd_USART(PRINT,params,length);
	free(params);

	delay_ms(1000);
}

void print_number(uint16_t value){
	send_cmd_USART(PRINT_NUMBER,&value,2);
	delay_ms(1000);
}

void print_error() {
	switch(errno) {
		case FRAME_ERROR_USART: {
			print_text("FE") ;
			break;
		}
		case PARITY_ERROR_USART: {
			print_text("PE");
			break;
		}
		case OVERFLOW_USART: {
			print_text("OE");
			break;
		}
		case EDOM: {
			// Defined by avr-libc
			print_text("EDOM");
			break;
		}
		case ERANGE: {
			// Defined by avr-libc
			print_text("ERANGE");
			break;
		}
		case 0: {
			print_text("No Error");
			break;
		}
		default: {
			// undefined error code
			print_text("Und. Err");
			break;
		}
	}
}

void turn_led_on(){
	PORTB = (1 << PORTB0);
}

void turn_led_off(){
	PORTB &= ~(1 << PORTB0);
}

void toggle_led(){
	PORTB ^= (1 << PORTB0);
}
